package com.album.activity;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Vector;

import com.album.activity.base.BaseActivity;
import com.album.activity.page.MenuBar;
import com.album.activity.page.Page;
import com.album.activity.page.PageManager;
import com.album.activity.pageView.CasualLookView;
import com.album.utils.CommonUtil;
import com.album.utils.MyLog;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

public class DefultActivity  implements PageManager{
	private static String TAG = DefultActivity.class.getCanonicalName();
    /** Called when the activity is first created. */
	private BroadcastReceiver mBroadCastRecv;

	private Handler mHanler;
	
	private Page currentPage;  // curren page
	private Vector<Page> pageStack;
	private HashMap<Class<? extends Page>, Page> pageMap;

	private LinearLayout mainContainer;
	private FrameLayout pageContainer;
	private MenuBar menuBar;
	private Context ctx;
	
	public DefultActivity(Context ctx){
		this.ctx= ctx;
		initView();
	}
	 
    public void initView(){
    	//计算屏幕大小  
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mainContainer = new LinearLayout(ctx);
        mainContainer.setOrientation(LinearLayout.VERTICAL); 
        initMenuBar();
        pageContainer = new FrameLayout(ctx);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT, 
				LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.weight = 1;
        pageContainer.setLayoutParams(lp);
        mainContainer.addView(pageContainer);
        
        mHanler = new Handler(){
        	@Override
        	public void handleMessage(Message msg) {
        		Object[] objs = (Object[])msg.obj;
        		Page page = (Page)objs[0];
        		msg.obj = objs[1];
        		page.handleMessage(msg);
        	}
        };
        pageStack = new Vector<Page>();
        pageMap = new HashMap<Class<? extends Page>, Page>();

       //初始界面 “随便看看”
        try {
			activePage(CasualLookView.class, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
	public void activePage(Class<? extends Page> pageClass, Object extra) throws Exception {
		MyLog.info(DefultActivity.class, "before page.size = " + pageStack.size());
		// check whether current page class equals pageClass
		if(currentPage != null && pageClass == currentPage.getClass()){
			MyLog.info(DefultActivity.class, "currentPage " + currentPage);
			return ;
		}
		Page forwardPage =  pageMap.get(pageClass);
		if(forwardPage == null){
			Constructor<? extends Page> pageConstructor = pageClass.getConstructor(getClass().getInterfaces()[0]);
			Log.i(TAG, "pageConstructor:"+pageConstructor+",getClass().getInterfaces()[0]"+getClass().getInterfaces()[0]);
			forwardPage = (Page)pageConstructor.newInstance(this);
			pageMap.put(pageClass, forwardPage);
			forwardPage.onCreate(extra);
		}else{
			pageStack.remove(forwardPage);
		}
		pageStack.add(forwardPage);  //add the page at the top of page stack
		
		if(currentPage != null){
			currentPage.onPause();
			if(!currentPage.isCanBack()){
				// page can not back, release the page.
				pageMap.remove(currentPage.getClass());
				pageStack.remove(currentPage);
				currentPage.onDestroy();
			}
		}
		
		currentPage = forwardPage;
		currentPage.onActive(extra);		
		menuBar.setMenuVisible(currentPage.isShowMenuBar());
		pageContainer.removeAllViews();
		pageContainer.addView(currentPage.getView());
		MyLog.info(DefultActivity.class, "after page.size = " + pageStack.size());
	}

	public void backToPrePage() throws Exception {
		if (pageStack.size() > 1) {
			pageStack.remove(pageStack.size() -1);
			Page prePage = pageStack.get(pageStack.size() - 1);
			activePage(prePage.getClass(), null);
		} else { 
		}
	}

	public void destroyPage(Class<? extends Page> pageClass) throws Exception {
		Page page = pageMap.get(pageClass);
		if (page != null) {
			// destroy page
			pageMap.remove(pageClass);
			pageStack.remove(page);
			page.onPause();
			page.onDestroy();
			
			// active prepage
			if (currentPage.equals(page)) {
				if (pageStack.size() > 0) {
					activePage(pageStack.lastElement().getClass(), null);
				} else {
					currentPage = null;
					pageContainer.removeAllViews();
				}
			}
		}
	}

	public Context getContext() {
		return ctx;
	}

	public void postMessage(Page page, Message msg) {
		if (msg != null && page != null) {
			Object[] objs = new Object[] { page, msg.obj };
			msg.obj = objs;
			mHanler.sendMessage(msg);
		}
	}
    
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if (keyCode == KeyEvent.KEYCODE_BACK && 
//				event.getAction() == KeyEvent.ACTION_DOWN) {
//			if(currentPage !=null && !currentPage.onKeyDown()){
//				try {
//					backToPrePage();
//					return true;
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}else{
//				return true;
//			}
//		}
//		return super.onKeyDown(keyCode, event);
//	}
//    
	public LinearLayout getView(){
		return mainContainer;
	}
	private void initMenuBar(){
        menuBar = new MenuBar(this,ctx);
		
		
		mainContainer.addView(menuBar.getView(), new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT, dip2px(ctx, 60)));
	}
	/**
	 *  dip to px  
	 */
	public int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	} 

//	@Override
//	public void onIntoScreen() {
//		// TODO Auto-generated method stub
//		
//	}
//
//	@Override
//	public void onLeaveScreen() {
//		// TODO Auto-generated method stub
//		
//	}
	
}
